package com.twinkle.rpc.common.serializer.mycoder;

import com.twinkle.rpc.common.message.MessageType;
import com.twinkle.rpc.common.message.RpcRequest;
import com.twinkle.rpc.common.message.RpcResponse;
import com.twinkle.rpc.common.serializer.myserializer.JsonSerializer;
import com.twinkle.rpc.common.serializer.myserializer.ObjectSerializer;
import com.twinkle.rpc.common.serializer.myserializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;


/**
 * @author twinkle
 * @version 1.0
 *   依次按照自定义的消息格式写入，传入的数据为request或者response
 *   需要持有一个serialize器，负责将传入的对象序列化成字节数组
 */
public class MyEncoder extends MessageToByteEncoder {
    private Serializer serializer;

    public MyEncoder(JsonSerializer jsonSerializer) {
        this.serializer = jsonSerializer;
    }

    public MyEncoder(ObjectSerializer objectSerializer) {
        this.serializer = objectSerializer;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
        //1.写入消息类型
        if (msg instanceof RpcRequest){
            out.writeShort(MessageType.REQUEST.getCode());
        } else if(msg instanceof RpcResponse) {
            out.writeShort(MessageType.RESPONSE.getCode());
        }
        //2.写入序列化方式
        out.writeShort(serializer.getType());
        //得到序列化数组
        byte[] serializeBytes = serializer.serialize(msg);
        //3.写入长度
        out.writeInt(serializeBytes.length);
        //4.写入序列化数组
        out.writeBytes(serializeBytes);
    }
}
